<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\logic;

use app\api\error\User as CommonUser;

/**
 * 用户接口逻辑
 */
class User extends ApiBase
{
	/**
	 * 修改密码
	 */
	public function setPassword($data)
	{
		$salt=db('user')->where('id',$data['user_id'])->value('salt');
		if(empty($salt)){
			return CommonUser::$paramError;
		}
		$datas['passwords']  = data_md5_key($data['passwords'],$salt);

		if( $msg = checkCode($data['username'],$data['code'],2)){
			return $msg;
		}
		$res=db('user')->where('id',$data['user_id'])->update($datas);
		if($res !== false){
			return $this->apiReturn();
		}else{
			return CommonUser::$paramError;
		}
	}
	/**
	 * 用户编辑
	 */
	public function sjAdd($data)
	{
		$is=db('sj')->where('user_id',$data['user_id'])->value('id');
		if(empty($is)){
			$res=db('sj')->insert(['user_id'=>$data['user_id'],'add_time'=>date('Y-m-d H:i:s')]);
		}else{
			$res=true;
		}
		if($res != false){
			return $this->apiReturn();
		}else{
			return CommonUser::$paramError;
		}
	}
	/**
	 * 查询
	 */
	public function getService($data)
	{
		$tjid=db('user')->where('id',$data['user_id'])->value('tjid');
		$arr=[];
		$info=db('user')->field('is,invitation,baodanid,tjid,nocodea,username')->where('id',$tjid)->find();
		if($info['is'] == 2){
			$arr['share']=$info['username'];
			$invitation=db('user')->where('id',$info['baodanid'])->value('username');
			$arr['service']=$invitation;
		}else{
			$tjinfo=db('user')->field('is,invitation,baodanid,tjid,username')->where('id',$info['tjid'])->find();
			if($tjinfo['is'] == 2){
				$arr['share']=$tjinfo['username'];
				$invitation=db('user')->where('id',$tjinfo['baodanid'])->value('username');
				$arr['service']=$invitation;
			}else{
				$str=substr($info['nocodea'],0,-1);
				$binfo=db('user')->field('id,invitation,username')->where(" is_service=1 and id IN (".$str.") and id!=".$_SESSION['user_id'])->order(" field(id,".$str.") desc")->find();
				$arr['share']=$binfo['username'];
				$arr['service']=$binfo['username'];
			}
		}
		return $arr;
	}
	/**
     * 服务中心
     */
	public function serviceList($data){
		$data['list_rows']=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$data['list_rows'];
		$where=" is_service=1 ";		
		$list=db('user')->field('id,headimg,username,phone,name,invitation')->where($where)->limit($page,$data['list_rows'])->order('id desc')->select();
		return $list;	
	}
	/**
	 * 用户编辑
	 */
    public function userEdit($data)
    {
		$arr=[];
		if(!empty($data['name'])){
			$arr['name']=$data['name'];
		}
		if(!empty($data['bank'])){
			$arr['bank']=$data['bank'];
		}
		if(!empty($data['bankCode'])){
			$arr['bankCode']=$data['bankCode'];
		}
		if(!empty($data['idcard'])){
			$arr['idcard']=$data['idcard'];
		}
        $res=db('user')->where('id',$data['user_id'])->update($arr);
		if($res != false){
			return $this->apiReturn();
		}else{
			return CommonUser::$paramError;
		}
    }
	/**
	 * 进入小组申请
	 */
	public function applyAdd($data)
	{
		$id=db('user')->where(['username'=>$data['share'],'is'=>2])->value('id');
		if(empty($id)){
			return CommonUser::$userError;
		}
		$baodanid=db('user')->where(['username'=>$data['baodan'],'is_service'=>1])->value('id');
		if(empty($baodanid)){
			return CommonUser::$userError;
		}
		$is=db('apply')->where('user_id',$data['user_id'])->value('id');
		if(!empty($is)){
			return CommonUser::$confirmFail;
		}
		$cont=[
			'user_id'=>$data['user_id'],
			'getid'=>$id,
			'baodanid'=>$baodanid,
			'create_time'=>time()
		];
		$res=db('apply')->insert($cont);
		if($res != false){
			db('user')->where('id',$data['user_id'])->update(['is'=>1]);
			return $this->apiReturn();
		}else{
			return CommonUser::$paramError;
		}
	}

	/**
	 * 用户
	 */
    public function headimgName($data)
    {
        $info=db('user')->field('id,headimg,name,phone')->where('id',$data['user_id'])->find();
		$info['headimg']=!empty($info['headimg'])?$info['headimg']:'/upload/headimg.png';
		$info['resume_id']=db('resume')->where('user_id',$data['user_id'])->value('resume_id');
		if(!empty($data['getid'])){
			$info['isms']=db('interview')->where(array('user_id'=>$data['getid'],'getid'=>$data['user_id']))->value('id');
		}
		return $info;
    }
	/**
	 * 用户接口逻辑
	 */
    public function getUserInfo($data)
    {
        $info=db('user')->where('id',$data['user_id'])->find();
		$info['tjnum']=db('user')->where("tjId=".$info['id'])->count();
		if($info['is'] == 1){
			$uinfo=db('dian')->where('user_id',$info['id'])->find();
			if(!empty($uinfo)){
				$cont_ids_array=str2arr($uinfo['img_ids']);
				foreach($cont_ids_array as $k=>$va){
					$cont_ids_array[$k]=get_picture_url($va);
				}
				$uinfo['cont_ids_array'] =$cont_ids_array;
				$uinfo['img']=get_picture_url($uinfo['img_id']);
				$info['dianinfo']=$uinfo;
			}

		}
		$info['dfk']=db('order_goods')->where('stat=0 and user_id='.$data['user_id'])->count();
		$info['dfh']=db('order_info')->alias('a')->join('order_goods b',' b.order_sn=a.order_sn')->where("a.stat=0 and a.is_xx=0 and b.stat=1 and b.user_id=".$data['user_id'])->count();
		$info['dsh']=db('order_info')->alias('a')->join('order_goods b',' b.order_sn=a.order_sn')->where("a.stat=1 and a.is_xx=0 and b.stat=1 and b.user_id=".$data['user_id'])->count();
		$info['dpj']=db('order_info')->alias('a')->join('order_goods b',' b.order_sn=a.order_sn')->where("a.stat=2 and a.is_xx=0 and b.stat=1 and b.user_id=".$data['user_id'])->count();
		//$info['dfk']=0;
		//$info['dfh']=0;
		//$info['dsh']=0;
		//$info['dpj']=0;
		$where="b.stat=1 and a.stat=1 and a.is_xx=1 and b.user_id=".$data['user_id'];
		$info['orderCount']=db('order_info')->alias('a')->join('order_goods b',' b.order_sn=a.order_sn')->where($where)->count();
		return $info;
    }
	/**
	 * 用户接口逻辑
	 */
	 public function checkUser($data){
		$name=db('user')->where(array('status'=>1,'username'=>$data['username']))->value('name');
		if(!empty($name)){
			return array('name'=>$name);
		}else{
			return CommonUser::$userError;
		}
	 }
	 /**
     * 余额明细
     */
    public function moneyyjLog($data)
    {
        $where = [];     
        !empty($data['user_id']) && $where['user_id'] = $data['user_id'];
		switch($data['is']){
			case 1;
				$where['type']=['<',50];
				break;
			case 2;
				$where['type']=[['>','49'],['<','100']];
				break;
			case 3;
				$where['type']=['>',99];
				break;
			default:
				$where['type']=['<',50];
		}
        $list=$this->modelMoneyyj->getList($where,'*','id DESC');
		foreach($list as $k=>$v){
			$list[$k]['msg']=moneyyjType($v['type'],$v['getid']);
		}
        return $list;
    }

	 /**
     * 分享收入明细
     */
    public function shareMoneyyj($data)
    {
        $list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		if($data['type'] == 1){
			$where="type=0 and user_id=".$data['user_id'];
		}else{
			$where="type IN(1,2,3,6) and user_id=".$data['user_id'];
		}
		$list=db('moneyyj')->where($where)->limit($page,$list_rows)->order("create_time desc")->select();
		foreach($list as $k=>$v){
			$list[$k]['msg']=moneyyjType($v['type'],$v['getid']);
		}
		return $list;
    }
	/**
	 * 二维码
	 */
	public function erweimaImg($data)
	{
		$cover_id=db('ad')->where('catid',14)->value('cover_id');
		$str=get_picture_url($cover_id);

		return $str;
	}
	/**
     * 二维码
     */
    public function erweima($data)
    {
		$code=db('user')->where('id',$data['user_id'])->value('invitation');
		if(empty($code)){
			$code=initcode();
			db('user')->where('id',$data['user_id'])->update(array('invitation'=>$code));
		}
		$url='http://'.$_SERVER['SERVER_NAME'].'/index.php/share/register?invitation='.$code;
		return $url;		
    }

	/**
     * 我的分享
     */
	public function tjList($data){
		$data['list_rows']=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$data['list_rows'];
		$where=" tjid=".$data['user_id'];
		if(isset($data['is_service'])){
			$where.=" and is_service=".$data['is_service'];
		}
		if(isset($data['is'])){
			$where.=" and `is`=".$data['is'];
		}
		if(!empty($data['grade'])){
			$where.=" and grade >=".$data['grade'];
		}else{
			$where.=" and grade=0";
		}

		$list=db('user')->field('id,headimg,phone,name,create_time,is_service,grade')->where($where)->limit($page,$data['list_rows'])->order('id desc')->select();
		foreach($list as $k=>$v){
			$list[$k]['num']=db('user')->where('tjid',$v['id'])->count();
			$str=$v['id'].',';
			$list[$k]['all']=db('user')->where("id != ".$v['id']." and nocodea like '%$str%'")->count();
			if($v['is_service']>0){
				$sum=db('moneyyj')->field("sum(money) as sum")->where(['user_id'=>$v['id'],'type'=>0])->find();
				$list[$k]['sum']=!empty($sum['sum'])?$sum['sum']:0;
			}
		}
		return $list;	
	}

	/**
     * 分享人数及收入
     */
    public function shareNum($data){
		$ids=','.$data['user_id'].',';
		$where=" ";
		if($data['type'] == 1){
			$where.=" and `is`=0 and is_service=0 and grade=0 ";
			//$info=db('moneyyj')->field("sum(money) as summoney")->where("type=0 and user_id=".$data['user_id'])->find();
		}elseif($data['type'] == 2){
			$where.=" and (grade>0 or is_service != 0)";
		}elseif($data['type'] == 3){
			$where.=" and `is`=1 ";
		}
		$share=db('user')->where("tjid=".$data['user_id'].$where)->count();
		$all=db('user')->where("id !=".$data['user_id']." and nocodea like '%$ids%'".$where)->count();
		$arr=array(
			'share'=>$share,
			'shareAll'=>$all,
			//'shareMoney'=>$info['summoney']?$info['summoney']:0,
			'invitation'=>db('user')->where('id',$data['user_id'])->value('invitation'),
		);
		return $arr;		
	}
	/**
     * 代理申请
     */
    public function agentApply($data)
    {		
		$arr=parse_config_array('agent_config');
		$num=db('user')->where('tjid',$data['user_id'])->count();
		if($num < $arr['num']){
			return ['code' => 1040001, 'msg' => '分享人数不足'.$arr['num'].'人，不能提交代理申请'];
		}else{
			$info=db('apply')->where('user_id',$data['user_id'])->find();
			if(empty($info)){
				db('apply')->insert(array('user_id'=>$data['user_id'],'create_time'=>time()));
				return $this->apiReturn();
			}else{
				return $info;
			}						
		}      	
    }
	/**
     * 权限明细
     */
	public function logList($data){
		$data['list_rows']=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$data['list_rows'];
		$where=" type=".$data['type']." and user_id=".$data['user_id'];
		$list=db('log')->where($where)->limit($page,$data['list_rows'])->order('id desc')->select();	
		foreach($list as $k=>$v){
			$list[$k]['message']=logType($v['type'],$v['key']);
		}
		return $list;	
	}
	/**
	 * 判断服务商
	 */
	public function isService($data)
	{
		$info=db('service')->where(array('code'=>$data['code']))->find();
		if(!empty($info)){
			$info['codes']=$info['code'];
			$info['headimg']=db('user')->where('id',$info['user_id'])->value('headimg');
			unset($info['code']);
			return $info;
		}else{
			return $this->apiReturn();
		}
	}
	/**
	 * 服务商申请
	 */
	public function agentAdd($data)
	{
		$id=db('agent')->where(array('code'=>$data['code'],'user_id'=>$data['user_id']))->value('id');
		if(!empty($id)){
			$res=db('agent')->where('id',$id)->save(array('create_time'=>time()));
		}else{
			$data['create_time']=time();
			$res=db('agent')->insert($data);
		}
		if($res !== false){
			return $this->apiReturn();
		}else{
			return CommonUser::$paramError;
		}
	}
}
